import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:oramemo/core/controllers/auth_controller.dart';
import 'package:oramemo/entity/device_mine_entity.dart';
import 'package:oramemo/pages/home/home_logic.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'dart:io';
import 'dart:ui' as ui;
import 'dart:typed_data';

import 'invcode_state.dart';

class InvcodeLogic extends GetxController {
  final InvcodeState state = InvcodeState();
  final GlobalKey qrKey = GlobalKey();
  
  @override
  void onInit() {
    super.onInit();
    // 初始化时获取圈子信息
    _loadCircleInfo();
  }
  
  // 加载圈子信息
  Future<void> _loadCircleInfo() async {
    state.isLoading.value = true;
    try {

      DeviceMineData? data= HomeLogic.to.state.currentDevice;
      
      // 设置圈子信息（实际项目中应从API获取）
      state.circleName.value = '${data?.deviceName??'我'}的时光机' ;
      state.circleId.value = 'circle_123456';
      final deviceId=data?.deviceId;
      final userName = AuthController.to.user?.userName;
      state.inviteCode.value = 'invite:deviceId=$deviceId&userName=$userName';
      state.avatarUrl.value = ''; // 实际项目中设置头像URL
      
    } catch (e) {
      Get.snackbar(
        '加载失败',
        '无法获取圈子信息，请稍后重试',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    } finally {
      state.isLoading.value = false;
    }
  }
  
  // 保存二维码到相册
  Future<void> saveToGallery() async {
    state.isSaving.value = true;
    try {

      // 请求存储权限
      // final status = await Permission.storage.request();
      final status = await PermissionUtil.photos();
      if (!status) {
        throw Exception('需要存储权限才能保存图片');
      }
      
      // 将二维码转换为图片
      final qrImage = await _captureQrCode();
      if (qrImage == null) {
        throw Exception('无法生成二维码图片');
      }
      
      // 保存到相册
      final result = await ImageGallerySaverPlus.saveImage(
        qrImage,
        quality: 100,
        name: '邀请码_${DateTime.now().millisecondsSinceEpoch}',
      );
      
      Get.snackbar(
        '保存成功',
        '邀请码已保存到相册',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    } catch (e) {
      Get.snackbar(
        '保存失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    } finally {
      state.isSaving.value = false;
    }
  }
  
  // 分享二维码
  Future<void> shareQrCode() async {
    state.isSharing.value = true;
    try {
      // 将二维码转换为图片
      final qrImage = await _captureQrCode();
      if (qrImage == null) {
        throw Exception('无法生成二维码图片');
      }
      
      // 创建临时文件
      final tempDir = await getTemporaryDirectory();
      final file = File('${tempDir.path}/invite_qr_code.png');
      await file.writeAsBytes(qrImage);
      
      // 分享文件
      await Share.shareXFiles(
        [XFile(file.path)],
        text: '扫描二维码加入"${state.circleName.value}"',
      );
    } catch (e) {
      Get.snackbar(
        '分享失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    } finally {
      state.isSharing.value = false;
    }
  }
  
  // 捕获二维码图像
  Future<Uint8List?> _captureQrCode() async {
    try {
      // 获取RenderRepaintBoundary
      final boundary = qrKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
      if (boundary == null) return null;
      
      // 将RenderRepaintBoundary转换为图像
      final image = await boundary.toImage(pixelRatio: 3.0);
      final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      
      return byteData?.buffer.asUint8List();
    } catch (e) {
      print('捕获二维码失败: $e');
      return null;
    }
  }
}
